package com.huxiu.pagers.mycomment;

import android.app.Activity;
import android.content.Intent;
import android.support.v4.content.LocalBroadcastManager;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.huxiu.APP;
import com.huxiu.R;
import com.huxiu.base.ZiXunDetailPager;
import com.huxiu.holder.MyCommentHolder;
import com.huxiu.net.GsonRequest;
import com.huxiu.net.NetworkConstants;
import com.huxiu.net.NetworkHelper;
import com.huxiu.net.model.CommentItem;
import com.huxiu.net.responses.CommentResponse;
import com.huxiu.utils.Constants;
import com.huxiu.utils.NetUtil;
import com.huxiu.utils.Utils;
import com.huxiu.view.RefreshListView;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;

import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;


public class MyComment extends ZiXunDetailPager {


    @ViewInject(R.id.lv_tabdetail_list)
    private RefreshListView lv_tabdetail_list;// 热门新闻列表

    @ViewInject(R.id.loading)
    private LinearLayout loading;// 加载动画
    @ViewInject(R.id.reLoadView)
    private LinearLayout reLoadView;// 加载中

    //什么也没有时的显示字样
    @ViewInject(R.id.nothing_ll)
    private LinearLayout nothing_ll;
    @ViewInject(R.id.nothing_text)
    private TextView nothing_text;

    public MyComment(Activity context) {
        super(context);
    }


    private int currentPage = 0;

    @Override
    protected View initView() {
        View viewAll = View.inflate(mContext, R.layout.list_detail, null);
        ViewUtils.inject(this, viewAll);
        // 给下拉刷新Listview设置监听器
        lv_tabdetail_list.setOnRefreshingListener(new MyOnRefreshingListener());
        return viewAll;
    }


    class MyOnItemClickListener implements AdapterView.OnItemClickListener {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position,
                                long id) {
            System.out.println("onItemClick:" + position);
            int realPosition = position - 2;

        }

    }


    @OnClick({R.id.reLoadView})
    public void mOnClick(View v) {
        switch (v.getId()) {
            case R.id.reLoadView:
                reLoadView.setVisibility(View.GONE);
                loading.setVisibility(View.VISIBLE);
                lv_tabdetail_list.setVisibility(View.VISIBLE);
                initData();
                break;
        }
    }
    @Override
    public void initData() {
        if (!NetUtil.checkNet(mContext)) {
            Utils.showToast(R.string.generic_check);
            reLoadView.setVisibility(View.VISIBLE);
            loading.setVisibility(View.INVISIBLE);
            lv_tabdetail_list.setVisibility(View.GONE);
            return;
        } else {
            reLoadView.setVisibility(View.GONE);
            loading.setVisibility(View.VISIBLE);
            lv_tabdetail_list.setVisibility(View.VISIBLE);
        }
        getDataFromServer();
    }

    private boolean isRefresh = false;// 当前是否是下拉刷新

    private boolean isLoadMore = false;// 当前是否是加载更多


    class MyOnRefreshingListener implements RefreshListView.OnRefreshingListener {
        @Override
        public void onRefreshing() {
            isRefresh = true;
            // 下拉刷新业务
            getDataFromServer();
        }

        @Override
        public void onLoadingMore() {
            if (currentPage < totalPages) {
                isLoadMore = true;
                // 加载更多业务
                getMoreDataFromServer();
            } else {
                lv_tabdetail_list.loadMoreFinished();
//                Utils.showToast(R.string.no_more);
                Toast.makeText(mContext, R.string.no_more, Toast.LENGTH_SHORT).show();
            }
        }
    }

    //上拉加载
    private void getMoreDataFromServer() {
        loadList(currentPage + 1);
    }

    //下拉刷新
    private void getDataFromServer() {
        loadList(0);
    }

    private List<CommentItem> lists = new ArrayList<>();
    private int totalPages = 0;

    //获取推荐页列表页数据
    private void loadList(final int page){
        String url = NetworkConstants.MY_POST_LIST;
        Map<String, String> params = new LinkedHashMap<>();
        params.put("page", Integer.toString(page));
        GsonRequest<CommentResponse> request = new GsonRequest<>(url, Request.Method.POST,
                CommentResponse.class, true, params,
                new Response.Listener<CommentResponse>() {
                    @Override
                    public void onResponse(CommentResponse response) {
                        if (response.isSuccess()) {
                            loading.setVisibility(View.INVISIBLE);
                            if (response.data.total == 0) {
                                nothing_ll.setVisibility(View.VISIBLE);
                                nothing_text.setText(R.string.no_comment_text);
                            } else {
                                nothing_ll.setVisibility(View.GONE);
                                if (page == 1) {
                                    lists.clear();
                                }
                                //发送给你广播数量
                                Intent intent = new Intent(Constants.INTENT_MYCOMMENT_NUM);
                                intent.putExtra(Constants.COMMENT_NUM,response.data.total);
                                LocalBroadcastManager.getInstance(APP.getInstance()).sendBroadcast(intent);
                                Collections.addAll(lists, response.data.datalist);
                                currentPage = response.data.cur_page;
                                totalPages = response.data.total_page;
                                parseListJson(lists);
                                // 如果当前是下拉刷新访问的网络，恢复下拉刷新界面
                                if (isRefresh) {
                                    lv_tabdetail_list.refreshFinished(true);
                                    isRefresh = false;
                                } else if (isLoadMore) {
                                    lv_tabdetail_list.loadMoreFinished();
                                    isLoadMore = false;
                                }
                            }

                        } else {
                            Utils.showToast(response.error.message);
                            // 如果当前是下拉刷新访问的网络，恢复下拉刷新界面
                            if (isRefresh) {
                                lv_tabdetail_list.refreshFinished(false);
                                isRefresh = false;
                            } else if (isLoadMore) {
                                lv_tabdetail_list.loadMoreFinished();
                                isLoadMore = false;
                            }
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Utils.showToast(R.string.generic_failure);
                // 如果当前是下拉刷新访问的网络，恢复下拉刷新界面
                if (isRefresh) {
                    lv_tabdetail_list.refreshFinished(false);
                    isRefresh = false;
                } else if (isLoadMore) {
                    lv_tabdetail_list.loadMoreFinished();
                    isLoadMore = false;
                }
            }
        });
        NetworkHelper.getInstance().addToRequestQueue(request);
    }

    private void parseListJson(List<CommentItem> lists) {
        if (!isLoadMore) {
            adapter = new SpareAdapter();
            lv_tabdetail_list.setAdapter(adapter);
        } else {
            adapter.notifyDataSetChanged();
        }
    }


    SpareAdapter adapter;

    private class SpareAdapter extends BaseAdapter {
        @Override
        public int getCount() {
            return lists.size();
        }

        @Override
        public Object getItem(int position) {
            return lists.get(position);
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            MyCommentHolder holder;
            View view = convertView;
            if (view == null) {
                 view = View.inflate(mContext, R.layout.item_mycomment_list, null);
                holder = new MyCommentHolder(view, mContext);
                view.setTag(holder);
            }
            holder = (MyCommentHolder) view.getTag();
            CommentItem item = lists.get(position);
            holder.setAdapter(adapter);
            holder.bindItem(item);//这里用来把获取到的数据传递给holder
            return view;
        }
    }
}
 